package com.example.librarymanagementproject2.mq;

import com.example.librarymanagementproject2.Common.config.RabbitConfig;
import com.example.librarymanagementproject2.converter.BookConverter;
import com.example.librarymanagementproject2.model.document.BookDocument;
import com.example.librarymanagementproject2.model.dto.BookWithCategoryDTO;
import com.example.librarymanagementproject2.model.entity.Book;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.stereotype.Component;

/**
 * @ClassName BookConsumer
 * @Description 图书消费者
 * @Author Kx
 * @Date 2025/10/27 19:43
 * @Version 1.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class BookConsumer {
    private final ElasticsearchOperations elasticsearchOperations;
    private final BookConverter bookConverter;

    /**
     * @author: kx
     * @date: 2025/10/27 20:03
     * @param bookWithCategoryDTO : 图书和图书分类数据传输信息
     * @description: 添加完图书信息后，将图书信息添加到Elasticsearch中
    */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitConfig.BOOK_INSERT_QUEUE, durable = "true"),
            exchange = @Exchange(name = RabbitConfig.BOOK_EXCHANGE, type = ExchangeTypes.DIRECT),
            key = RabbitConfig.BOOK_INSERT_ROUTING_KEY
    ))
    public void receive(BookWithCategoryDTO bookWithCategoryDTO) {
        // 把图书信息和图书分类信息转换成图书文档信息
        BookDocument bookDocument = bookConverter.bookToBookDocument(bookWithCategoryDTO.getBook(), bookWithCategoryDTO.getBookCategory());

        // 添加文档信息
        elasticsearchOperations.save(bookDocument);
    }

    /**
     * @author: kx
     * @date: 2025/10/29 10:47
     * @param bookWithCategoryDTO : 图书和图书分类数据传输信息
     * @description: 修改图书状态成功后，将图书信息修改到Elasticsearch中
    */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitConfig.BOOK_OPERATION_QUEUE, durable = "true"),
            exchange = @Exchange(name = RabbitConfig.BOOK_EXCHANGE, type = ExchangeTypes.DIRECT),
            key = RabbitConfig.BOOK_OPERATION_ROUTING_KEY
    ))
    public void updateBookStatus(BookWithCategoryDTO bookWithCategoryDTO) {
        // 把图书信息和图书分类信息转换成图书文档信息
        BookDocument bookDocument = bookConverter.bookToBookDocument(bookWithCategoryDTO.getBook(), bookWithCategoryDTO.getBookCategory());

        // 修改文档信息
        elasticsearchOperations.update(bookDocument);
    }
}
